<template>
  <el-row :gutter="10">
    <el-col :xl="8" :lg="8" :md="24" :sm="24" :xs="24">
      <!-- 订单信息 -->
      <OrderBasicInfo :order-data="orderData">
        <template #tool>
          <div class="flex justify-end w-full">
            <el-button
              v-if="orderData.status! === TradeOrderStatusEnum.UNPAID.status"
              type="primary"
              plain
              @click="updatePrice"
            >
              订单改价
            </el-button>
            <!-- <el-button>退款</el-button> -->
            <!-- 待发货 -->
            <template v-if="orderData.status! === TradeOrderStatusEnum.UNDELIVERED.status">
              <!-- 快递发货 -->
              <el-button
                v-if="orderData.deliveryType === DeliveryTypeEnum.EXPRESS.type"
                type="primary"
                plain
                @click="delivery"
              >
                确认发货
              </el-button>
              <!-- 到店自提 -->
              <el-button
                v-if="orderData.deliveryType === DeliveryTypeEnum.PICK_UP.type && showPickUp"
                type="primary"
                plain
                @click="handlePickUp"
              >
                订单核销
              </el-button>
            </template>
          </div>
        </template>
      </OrderBasicInfo>
    </el-col>
    <el-col :xl="8" :lg="8" :md="24" :sm="24" :xs="24">
      <!-- 会员信息 -->
      <OrderMemberInfo :order-data="orderData">
        <template #tool>
          <div class="w-full flex h-32px items-center justify-end">
            ID:{{ orderData?.user?.id }} <Icon icon="ep:shop" :size="16" />
          </div>
        </template>
      </OrderMemberInfo>
    </el-col>
    <el-col :xl="8" :lg="8" :md="24" :sm="24" :xs="24">
      <OrderStatusInfo :order-data="orderData">
        <template #tool>
          <div class="flex justify-end w-full">
            <!-- <el-button>打印小票 </el-button>

            <el-button>电子合同 </el-button> -->

            <el-button type="primary" @click="remark">商家备注</el-button>
          </div>
        </template>
      </OrderStatusInfo>
    </el-col>
  </el-row>
  <!-- 结算信息 -->
  <ContentWrap
    class="!mb-10px"
    v-if="
      (orderData?.orderReasons && orderData?.orderReasons.length) ||
      (orderData?.orderStoreReasons && orderData?.orderStoreReasons.length)
    "
  >
    <el-descriptions
      title="门店备注"
      :column="1"
      v-if="orderData?.orderStoreReasons && orderData?.orderStoreReasons.length"
    >
      <!-- 第一层 -->
      <el-descriptions-item>
        <el-text v-for="(item, index) in orderData?.orderStoreReasons" :key="index">
          <dict-tag :type="DICT_TYPE.TENANT_IDENTITY" :value="item.source" />
          {{ item.nodeName }} {{ item.creator }} {{ formatDate(item.createTime) }}【<el-text
            type="primary"
            >{{ item.reason }} </el-text
          >】
        </el-text>
      </el-descriptions-item>
    </el-descriptions>
    <el-descriptions
      title="总部备注"
      :column="1"
      v-if="orderData?.orderReasons && orderData?.orderReasons.length"
    >
      <!-- 第一层 -->
      <el-descriptions-item>
        <el-text v-for="(item, index) in orderData?.orderReasons" :key="index">
          {{ item.creator.split(':')[1] }} (ID:{{ item.creator.split(':')[0] }})
          {{ formatDate(item.createTime) }}【<el-text type="primary">{{ item.reason }} </el-text>】
        </el-text>
      </el-descriptions-item>
    </el-descriptions>
  </ContentWrap>
  <!-- 商品信息 -->
  <OrderGoodsInfo :goods-list="orderData.items">
    <template #extension v-if="[2, 10, 20, 30, 4, 80].includes(orderData.status)">
      <el-table-column align="center" :min-width="70" label="操作">
        <template #default="{ row }"
          ><el-button
            link
            @click="handleRefund(row)"
            :disabled="row.afterSaleStatus != 0"
            type="primary"
            >售后</el-button
          ></template
        >
      </el-table-column>
    </template></OrderGoodsInfo
  >
  <!-- 结算信息 -->
  <ContentWrap class="!mb-10px">
    <el-descriptions title="结算信息" :column="1">
      <!-- 第一层 -->
      <el-descriptions-item>
        <el-text class="mr-5px!">您总计购买{{ orderData.productCount }}个商品</el-text>
        <el-text class="mr-5px!">原价总计:{{ fenToYuan(orderData.totalPrice!) }}元 </el-text>
        <el-text class="mr-5px!">总计优惠:{{ fenToYuan(orderData.givePrice!) }}元 </el-text>
        <el-text class="mr-5px!">订单实售:{{ fenToYuan(orderData.realPrice!) }}元 </el-text>
        <el-text class="mr-5px!">实付金额:{{ fenToYuan(orderData.otherPrice!) }}元 </el-text>
        <el-text :class="{ 'c-red!': orderData.leavePrice > 0 }"
          >剩余欠款:{{ fenToYuan(orderData.leavePrice!) }} 元 </el-text
        >
      </el-descriptions-item>
    </el-descriptions>
  </ContentWrap>

  <ContentWrap class="!mb-10px" v-if="orderData.orderRespVO2?.discountpay.length > 0">
    <el-descriptions title="优惠明细" :column="1">
      <!-- 第二层 -->
      <el-descriptions-item v-for="item in orderData.orderRespVO2?.discountpay" :key="item">
        {{ item }}</el-descriptions-item
      >
      <!-- <el-descriptions-item>
        <template #label><span style="color: red">优惠劵优惠: </span></template>
        {{ fenToYuan(orderData.couponPrice!) }} 元
      </el-descriptions-item> -->
      <!-- <el-descriptions-item>
        <template #label><span style="color: red">VIP 优惠: </span></template>
        {{ fenToYuan(orderData.vipPrice!) }} 元
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label><span style="color: red">活动优惠: </span></template>
        {{ fenToYuan(orderData.discountPrice!) }} 元
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label><span style="color: red">积分抵扣: </span></template>
        {{ fenToYuan(orderData.pointPrice!) }} 元
      </el-descriptions-item> -->
    </el-descriptions>
  </ContentWrap>
  <ContentWrap
    class="!mb-10px"
    v-if="
      orderData.orderRespVO2?.otherpay.length > 0 || orderData.orderRespVO2?.assetpay.length > 0
    "
  >
    <el-descriptions title="支付信息" :column="1">
      <!-- 第二层 -->
      <el-descriptions-item v-if="orderData.orderRespVO2?.otherpay.length > 0">
        <template #label><span style="color: red">实付金额: </span></template>
        <div v-for="item in orderData.orderRespVO2?.otherpay" :key="item"> {{ item }}</div>
      </el-descriptions-item>
      <el-descriptions-item v-if="orderData.orderRespVO2?.assetpay.length > 0">
        <template #label><span style="color: red">资产抵扣: </span></template>
        <div v-for="item in orderData.orderRespVO2?.assetpay" :key="item"> {{ item }}</div>
      </el-descriptions-item>
    </el-descriptions>
  </ContentWrap>
  <!-- 还款信息 -->
  <OrderRefundGoodsInfo v-if="false" />
  <!-- 销售信息 -->
  <ContentWrap class="!mb-10px">
    <el-descriptions title="销售信息" :column="1">
      <el-descriptions-item> 销售门店:{{ orderData?.nodeName }} </el-descriptions-item>
      <!-- 第一层 -->
      <el-descriptions-item v-if="orderData?.rebateType == 0">
        销售员工:
        <span v-for="item in orderData.employeeStr" :key="item" class="mr-5px">
          {{ item.employeeName }} (ID:{{ item.employeeId }}):{{ item.proportion }}%</span
        >
      </el-descriptions-item>
    </el-descriptions>
  </ContentWrap>
  <ContentWrap class="!mb-10px">
    <!-- 物流信息 -->
    <el-descriptions :column="4" title="核销 | 收货信息">
      <el-descriptions-item label="配送方式: ">
        <dict-tag :type="DICT_TYPE.TRADE_DELIVERY_TYPE" :value="orderData.deliveryType!" />
      </el-descriptions-item>
      <el-descriptions-item label="收货人:">{{ orderData.receiverName }}</el-descriptions-item>
      <el-descriptions-item label="联系电话:">{{ orderData.receiverMobile }}</el-descriptions-item>
      <!-- 快递配送 -->
      <div v-if="orderData.deliveryType === DeliveryTypeEnum.EXPRESS.type">
        <el-descriptions-item v-if="orderData.receiverDetailAddress" label="收货地址: ">
          {{ orderData.receiverAreaName }} {{ orderData.receiverDetailAddress }}
          <!-- 待发货 -->
          <template v-if="orderData.status! === TradeOrderStatusEnum.UNDELIVERED.status">
            <el-link
              v-if="orderData.deliveryType === DeliveryTypeEnum.EXPRESS.type"
              @click="updateAddress"
            >
              <Icon icon="ep:edit" :size="14" class="color-[var(--el-color-primary)]" />
            </el-link>
          </template>
          <el-link
            class="ml-5px"
            @click.stop="
              copyContent(
                `${orderData.receiverName} ${orderData.receiverMobile} ${orderData.receiverDetailAddress}`
              )
            "
            type="primary"
          >
            <Icon icon="ep:document-copy" :size="14" class="color-[var(--el-color-primary)]" />
          </el-link>
        </el-descriptions-item>
        <el-descriptions-item v-if="orderData.logisticsId" label="物流公司: ">
          {{ deliveryExpressList.find((item) => item.id === orderData.logisticsId)?.name }}
        </el-descriptions-item>
        <el-descriptions-item v-if="orderData.logisticsId" label="运单号: ">
          {{ orderData.logisticsNo }}
        </el-descriptions-item>
        <el-descriptions-item v-if="formatDate.deliveryTime" label="发货时间: ">
          {{ formatDate(orderData.deliveryTime) }}
        </el-descriptions-item>
        <el-descriptions-item v-for="item in 2" :key="item" label-class-name="no-colon" />
        <el-descriptions-item v-if="expressTrackList.length > 0" label="物流详情: ">
          <el-timeline>
            <el-timeline-item
              v-for="(express, index) in expressTrackList"
              :key="index"
              :timestamp="formatDate(express.time)"
            >
              {{ express.content }}
            </el-timeline-item>
          </el-timeline>
        </el-descriptions-item>
      </div>
      <!-- 自提门店 -->
      <div v-if="orderData.deliveryType === DeliveryTypeEnum.PICK_UP.type">
        <el-descriptions-item v-if="orderData.pickUpStoreId" label="自提门店: ">
          {{ pickUpStore?.name }}
        </el-descriptions-item>
        <!-- <el-descriptions-item v-if="orderData.pickUpStoreId" label="核销员工: ">
        {{ pickUpStore?.name }}
      </el-descriptions-item>
      <el-descriptions-item v-if="orderData.pickUpStoreId" label="核销会员姓名: ">
        {{ pickUpStore?.name }}
      </el-descriptions-item>
      <el-descriptions-item v-if="orderData.pickUpStoreId" label="核销会员性别: ">
        {{ pickUpStore?.name }}
      </el-descriptions-item>
      <el-descriptions-item v-if="orderData.pickUpStoreId" label="核销会员手机: ">
        {{ pickUpStore?.name }}
      </el-descriptions-item> -->
      </div>
    </el-descriptions>
  </ContentWrap>
  <ContentWrap class="!mb-10px">
    <!-- 订单日志 -->
    <el-descriptions title="订单操作日志">
      <el-descriptions-item labelClassName="no-colon">
        <el-timeline>
          <el-timeline-item
            v-for="(log, index) in orderData.logs"
            :key="index"
            :timestamp="formatDate(log.createTime!)"
            placement="top"
          >
            <div :class="[isDark ? 'el-timeline-right-content-dark' : 'el-timeline-right-content']">
              {{ log.content }}
            </div>
            <template #dot>
              <span
                :style="{ backgroundColor: getUserTypeColor(log.userType!) }"
                class="dot-node-style"
              >
                {{ getDictLabel(DICT_TYPE.USER_TYPE, log.userType)[0] }}
              </span>
            </template>
          </el-timeline-item>
        </el-timeline>
      </el-descriptions-item>
    </el-descriptions>
  </ContentWrap>

  <!-- 各种操作的弹窗 -->
  <OrderDeliveryForm ref="deliveryFormRef" @success="getDetail" />
  <OrderUpdateRemarkForm ref="updateRemarkForm" @success="getDetail" />
  <OrderUpdateAddressForm ref="updateAddressFormRef" @success="getDetail" />
  <OrderUpdatePriceForm ref="updatePriceFormRef" @success="getDetail" />
</template>
<script lang="ts" setup>
import * as TradeOrderApi from '@/api/mall/trade/order'
import * as ShopTradeOrderApi from '@/api/shop/trade/order'

import { fenToYuan } from '@/utils'
import { formatDate } from '@/utils/formatTime'
import { DICT_TYPE, getDictLabel, getDictObj } from '@/utils/dict'
import OrderUpdateRemarkForm from '@/views/mall/trade/order/form/OrderUpdateRemarkForm.vue'
import OrderDeliveryForm from '@/views/mall/trade/order/form/OrderDeliveryForm.vue'
import OrderUpdateAddressForm from '@/views/mall/trade/order/form/OrderUpdateAddressForm.vue'
import OrderUpdatePriceForm from '@/views/mall/trade/order/form/OrderUpdatePriceForm.vue'
import * as DeliveryExpressApi from '@/api/mall/trade/delivery/express'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { DeliveryTypeEnum, TradeOrderStatusEnum } from '@/utils/constants'
import * as DeliveryPickUpStoreApi from '@/api/mall/trade/delivery/pickUpStore'
import { propTypes } from '@/utils/propTypes'
import {
  OrderBasicInfo,
  OrderMemberInfo,
  OrderStatusInfo,
  OrderGoodsInfo,
  OrderRefundGoodsInfo
} from '../components'

const appStore = useAppStore()

const isDark = computed(() => appStore.getIsDark)

defineOptions({ name: 'TradeOrderDetail' })

const message = useMessage() // 消息弹窗

/** 获得 userType 颜色 */
const getUserTypeColor = (type: number) => {
  const dict = getDictObj(DICT_TYPE.USER_TYPE, type)
  switch (dict?.colorType) {
    case 'success':
      return '#67C23A'
    case 'info':
      return '#909399'
    case 'warning':
      return '#E6A23C'
    case 'danger':
      return '#F56C6C'
  }
  return '#165DFF'
}

// 订单详情
const orderData = ref<TradeOrderApi.OrderVO>({
  logs: []
})

/** 各种操作 */
const updateRemarkForm = ref() // 订单备注表单 Ref
const remark = () => {
  updateRemarkForm.value?.open(orderData.value)
}
const deliveryFormRef = ref() // 发货表单 Ref
const delivery = () => {
  deliveryFormRef.value?.open(orderData.value)
}
const updateAddressFormRef = ref() // 收货地址表单 Ref
const updateAddress = () => {
  updateAddressFormRef.value?.open(orderData.value)
}
const updatePriceFormRef = ref() // 订单调价表单 Ref
const updatePrice = () => {
  updatePriceFormRef.value?.open(orderData.value)
}
/** 退款 */
const handleRefund = async (row) => {
  try {
    // 二次确认
    await message.confirm('确认申请退款吗？')
    // 提交
    await ShopTradeOrderApi.adminRefundId({ id: row.id })
    message.success('申请成功')
    // 刷新列表
    await getDetail()
  } catch {}
}

/** 核销 */
const handlePickUp = async () => {
  try {
    // 二次确认
    await message.confirm('确认核销订单吗？')
    // 提交
    await TradeOrderApi.pickUpOrder(orderData.value.id!)
    message.success('核销成功')
    // 刷新列表
    await getDetail()
  } catch {}
}

/** 获得详情 */
const { params } = useRoute() // 查询参数
const props = defineProps({
  id: propTypes.number.def(undefined), // 订单ID
  showPickUp: propTypes.bool.def(true) // 显示核销按钮
})
const id = (params.id || props.id) as unknown as number
const getDetail = async () => {
  if (id) {
    const res = (await TradeOrderApi.getOrder(id)) as TradeOrderApi.OrderVO
    // 没有表单信息则关闭页面返回
    if (!res) {
      message.error('交易订单不存在')
      close()
    }
    orderData.value = res
  }
}

/** 关闭 tag */
const { delView } = useTagsViewStore() // 视图操作
const { push, currentRoute } = useRouter() // 路由
const close = () => {
  delView(unref(currentRoute))
  push({ name: 'TradeOrder' })
}

/** 复制 */
import { useClipboard } from '@vueuse/core'
import { useAppStore } from '@/store/modules/app'
const { copy } = useClipboard() // 初始化 copy 到粘贴板
const copyContent = async (content) => {
  await copy(content)
  message.success('复制成功！')
}

/** 初始化 **/
const deliveryExpressList = ref([]) // 物流公司
const expressTrackList = ref([]) // 物流详情
const pickUpStore = ref({}) // 自提门店
onMounted(async () => {
  await getDetail()
  // 如果配送方式为快递，则查询物流公司
  if (orderData.value.deliveryType === DeliveryTypeEnum.EXPRESS.type) {
    deliveryExpressList.value = await DeliveryExpressApi.getSimpleDeliveryExpressList()
    if (orderData.value.logisticsId) {
      expressTrackList.value = await TradeOrderApi.getExpressTrackList(orderData.value.id!)
    }
  } else if (orderData.value.deliveryType === DeliveryTypeEnum.PICK_UP.type) {
    pickUpStore.value = await DeliveryPickUpStoreApi.getDeliveryPickUpStore(
      orderData.value.pickUpStoreId
    )
  }
})
</script>

<style lang="scss" scoped>
:deep(.el-descriptions) {
  &:not(:nth-child(1)) {
    margin-top: 20px;
  }

  .el-descriptions__title {
    display: flex;
    align-items: center;
  }

  .el-descriptions-item__container {
    margin: 0 10px;

    .no-colon {
      margin: 0;

      &::after {
        content: '';
      }
    }
  }
}

// 时间线样式调整
:deep(.el-timeline) {
  margin: 10px 0 0 160px;

  .el-timeline-item__wrapper {
    position: relative;
    top: -20px;

    .el-timeline-item__timestamp {
      position: absolute !important;
      top: 10px;
      left: -150px;
    }
  }

  .el-timeline-right-content {
    display: flex;
    align-items: center;
    min-height: 30px;
    padding: 10px;
    border-radius: var(--el-card-border-radius);
    background-color: var(--app-content-bg-color);

    &::before {
      position: absolute;
      top: 10px;
      left: 13px; /* 将伪元素水平居中 */
      border-color: transparent var(--app-content-bg-color) transparent transparent; /* 尖角颜色，左侧朝向 */
      border-style: solid;
      border-width: 8px; /* 调整尖角大小 */
      content: ''; /* 必须设置 content 属性 */
    }
    &-dark {
      display: flex;
      align-items: center;
      min-height: 30px;
      padding: 10px;
      border-radius: var(--el-card-border-radius);
      background-color: var(--el-bg-color);

      &::before {
        position: absolute;
        top: 10px;
        left: 13px; /* 将伪元素水平居中 */
        border-color: transparent var(--el-bg-color) transparent transparent; /* 尖角颜色，左侧朝向 */
        border-style: solid;
        border-width: 8px; /* 调整尖角大小 */
        content: ''; /* 必须设置 content 属性 */
      }
    }
  }

  .dot-node-style {
    position: absolute;
    left: -5px;
    display: flex;
    width: 20px;
    height: 20px;
    font-size: 10px;
    color: #fff;
    border-radius: 50%;
    justify-content: center;
    align-items: center;
  }
}
</style>
